package itsm.isperp.module.controller.app;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.quartz.domain.JobState;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.app.AppJob;
import itsm.isperp.module.service.app.AppJobSchedulerService;
import itsm.isperp.module.service.app.AppJobService;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.JobDetailImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fr.third.org.quartz.JobExecutionContext;

/**
 * 系统帮助的控制器
 * 
 * @author lizx
 * @date 2013-7-27
 */
@Controller
@RequestMapping("app/job")
public class AppJobController extends BaseController<AppJob> {

	@Autowired
	protected AppJobService appJobService;

	@Override
	public AppJobService getService() {
		return this.appJobService;
	}

	@Override
	public String getPageTitle() {
		return "系统服务";
	}

	/**
	 * 编辑界面
	 * 
	 * @param id
	 *            唯一标识
	 * @return 编辑视图
	 */
	@RequestMapping("edit")
	public ModelAndView edit(String id, HttpServletRequest req)
			throws Exception {

		AppJob job = this.getService().findOne(id);
		if (job == null) {
			job = new AppJob();
			job.setStatus(JobState.stop);
			job.setId(HibernateUUIDGenerator.generate());
		}

		ModelAndView mv = this.getModelAndView();
		mv.addObject("model", job);
		return mv;
	}

	@RequestMapping("delete")
	@ResponseBody
	public ResultMessage delete(String id, HttpServletRequest req) {
		AppJob job = this.getService().findOne(id);
		if (!"stop".equals(job.getStatus())) {
			return ResultMessage.failure("请停止后再删除！");
		}
		this.getService().delete(id);
		return ResultMessage.newInstance(true);
	}

	@RequestMapping("changeStatus")
	@ResponseBody
	public ResultMessage changeStatus(String id, String status) {
		Set<String> value = new HashSet<>();
		value.add("status");
		AppJob job = this.getService().findOne(id);
		if (job == null) {
			return ResultMessage.failure("实体不存在！");
		}

		JobState oldStatus = JobState.valueOf(job.getStatus());

		JobState newStatus = JobState.valueOf(status);
		// 状态相同，不做处理
		if (oldStatus == newStatus) {
			return ResultMessage.failure("任务状态不需要更新！");
		}

		switch (oldStatus) {
		case run:
			// 正在运行只接受停止动作
			if (newStatus != JobState.stopping) {
				return ResultMessage.failure("已经启动的任务只能执行停止操作！");
			}
			job.setStatus(JobState.stopping);
			break;
		case running:
			return ResultMessage.failure("任务正在启动中，请稍候！");

		case stop:
			// 正在运行只接受停止动作
			if (newStatus != JobState.running) {
				return ResultMessage.failure("已经停止的任务只能执行启动操作！");
			}
			job.setStatus(JobState.running);
			break;
		case stopping:
			return ResultMessage.failure("任务正在停止中，请稍候！");
		}

		this.getService().saveOrUpdateSpecific(job, value);
		return ResultMessage.success();
	}

	@RequestMapping("runJob")
	@ResponseBody
	public ResultMessage runJob(String id, String beanId) {

		if (StringUtils.isEmpty(beanId)) {
			return ResultMessage.failure("beanId不能为空！");
		}

		AppJobSchedulerService appJobSchedulerService = ContextHolder
				.getSpringBean("appJobSchedulerService");
		try {
			JobKey jobKey = new JobKey(AppJobService.JOB_PREFIX + id,
					AppJobService.companyId);

			Scheduler scheduler;

			scheduler = appJobSchedulerService.retrieveScheduler();
			scheduler.triggerJob(jobKey);
		} catch (SchedulerException e) {

			return ResultMessage.failure(e.getMessage());
		}

		return ResultMessage.success("执行成功！");

	}
}
